package org.pcorp.battlespace.construction.ui.admin.equipement;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import org.pcorp.battlespace.construction.ui.tools.DataCellEditor;
import org.pcorp.battlespace.construction.ui.tools.DialogUi;
import org.pcorp.battlespace.modele.Capacite;
import org.pcorp.battlespace.modele.Equipement;

public class ModaleCapaciteAdmin extends DialogUi {
	private static final long serialVersionUID = -3956864355081153819L;
	private Equipement equip;
	private JTable table;
	private List<Capacite> capacites;
	
	public ModaleCapaciteAdmin(Component parent, Equipement equip, List<Capacite> capacites) {
		super(JOptionPane.getFrameForComponent(parent), true);
		this.setLayout(new GridBagLayout());
		this.setSize(350, 250);
		this.setLocationRelativeTo(null);
		this.setResizable(false);
		this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		this.setTitle("Cap : " + equip.getNom());
		this.equip = equip;
		this.capacites = capacites;
		build();
	}
	
	public void build() {
		setLayout(new GridBagLayout());
		GridBagConstraints gbc = new GridBagConstraints();
		
		gbc.gridx     = gbc.gridy      = 0;
		gbc.weightx   = gbc.weighty    = 1;
		gbc.gridwidth = gbc.gridheight = 1;
	    gbc.fill = GridBagConstraints.BOTH;
	    
	    ModelTableCapaciteAdmin model = new ModelTableCapaciteAdmin(capacites, equip);
	    table = new JTable(model);
	    table.getColumnModel().getColumn(ModelTableCapaciteAdmin.VALMIN).setCellEditor(new DataCellEditor());
	    table.getColumnModel().getColumn(ModelTableCapaciteAdmin.VALMAX).setCellEditor(new DataCellEditor());
	    JScrollPane scrollPane = new JScrollPane(table);
	    add(scrollPane, gbc);
	    
	    
	    this.addWindowListener(new WindowAdapter(){
	        @Override
	        public void windowClosing(WindowEvent e) {
	        	if (table.getCellEditor()!=null)
	        		table.getCellEditor().stopCellEditing();
	            equip.getCapacites().clear();
	            for (Capacite capacite : capacites) {
					if (capacite.getValeurMax()!=0 || capacite.getValeurMin()!=0) {
						equip.getCapacites().add(capacite);
					}
				}
	            equip.setUpdate(true);
	        }
	    });
	}
	
	public static void openForm(Component parent, Equipement equip, List<Capacite> capacites) {
		ModaleCapaciteAdmin form = new ModaleCapaciteAdmin(parent, equip, capacites);
		form.setVisible(true);
	}
	
	
}
